<template>
  <div class="user">
    <!-- 面包屑导航区域 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
      <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片视图区域 -->
    <el-card class="user-box">
      <el-row>
        <el-col :span="7">
          <el-input
            placeholder="请输入内容"
            v-model="queryInfo.query"
            clearable
            @clear="getUserList"
          >
            <el-button
              slot="append"
              icon="el-icon-search"
              @click="getUserList"
            ></el-button>
          </el-input>
        </el-col>
        <el-col :span="4">
          <el-button type="primary" @click="dialogFormVisible = true"
            >添加用户</el-button
          >
        </el-col>
      </el-row>

      <!-- 用户列表区域 -->
      <el-table :data="userList" style="width: 100%" border stripe>
        <el-table-column type="index" width="50"> </el-table-column>
        <el-table-column prop="username" label="姓名"> </el-table-column>
        <el-table-column prop="email" label="邮箱"> </el-table-column>
        <el-table-column prop="mobile" label="电话"> </el-table-column>
        <el-table-column prop="role_name" label="角色"> </el-table-column>
        <el-table-column label="状态">
          <template slot-scope="scope">
            <el-switch
              v-model="scope.row.mg_state"
              @change="userStateChanged(scope.row.id, scope.row.mg_state)"
            >
            </el-switch>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="175">
          <template slot-scope="scope">
            <!-- 修改按钮 -->
            <el-button
              type="primary"
              icon="el-icon-edit"
              size="mini"
              @click="showEditDialog(scope.row.id)"
            ></el-button>
            <!-- 删除按钮 -->
            <el-button
              type="danger"
              icon="el-icon-delete"
              size="mini"
              @click="delUser(scope.row.id)"
            ></el-button>
            <!-- 分配角色按钮 -->
            <el-tooltip
              effect="dark"
              content="分配角色"
              placement="top"
              :enterable="false"
            >
              <el-button
                type="warning"
                icon="el-icon-setting"
                size="mini"
                @click="showSetRole(scope.row)"
              ></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页区域 -->
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="queryInfo.pagenum"
        :page-sizes="[1, 2, 5, 10]"
        :page-size="queryInfo.pagesize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      >
      </el-pagination>
    </el-card>

    <!-- 添加用户弹窗对话框 -->
    <el-dialog
      title="添加用户"
      :visible.sync="dialogFormVisible"
      @close="addDialogClosed"
      width="50%"
    >
      <!-- 对话框内容主体 -->
      <el-form :model="addForm" :rules="addRules" ref="addFormRef">
        <el-form-item
          label="用户名"
          :label-width="formLabelWidth"
          prop="username"
        >
          <el-input v-model="addForm.username" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item
          label="密码"
          :label-width="formLabelWidth"
          prop="password"
        >
          <el-input v-model="addForm.password" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="邮箱" :label-width="formLabelWidth" prop="email">
          <el-input v-model="addForm.email" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="手机" :label-width="formLabelWidth" prop="mobile">
          <el-input v-model="addForm.mobile" autocomplete="off"></el-input>
        </el-form-item>
      </el-form>
      <!-- 对话框底部 -->
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="addUser">确 定</el-button>
      </div>
    </el-dialog>

    <!-- 修改用户信息对话框 -->
    <el-dialog
      title="修改用户信息"
      :visible.sync="editDialogVisible"
      width="50%"
      @close="editDialogClosed"
    >
      <!-- 对话框内容主体 -->
      <el-form :model="editForm" :rules="addRules" ref="editFormRef">
        <el-form-item label="用户名" :label-width="formLabelWidth">
          <el-input
            v-model="editForm.username"
            autocomplete="off"
            disabled
          ></el-input>
        </el-form-item>
        <el-form-item label="邮箱" :label-width="formLabelWidth" prop="email">
          <el-input v-model="editForm.email" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="手机" :label-width="formLabelWidth" prop="mobile">
          <el-input v-model="editForm.mobile" autocomplete="off"></el-input>
        </el-form-item>
      </el-form>
      <!-- 对话框底部 -->
      <span slot="footer" class="dialog-footer">
        <el-button @click="editDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="editUser(editForm.id)"
          >确 定</el-button
        >
      </span>
    </el-dialog>

    <!-- 角色分配对话框 -->
    <el-dialog
      title="分配角色"
      :visible.sync="setRoleVisible"
      width="50%"
      @close="resetSelectRole"
    >
      <div class="userInfo">
        <p>当前的用户：{{ usersInfo.username }}</p>
        <p>当前的角色：{{ usersInfo.role_name }}</p>
        <p>
          分配新角色：
          <el-select v-model="selectedRole" placeholder="请选择">
            <el-option
              v-for="item in roleList"
              :key="item.id"
              :label="item.roleName"
              :value="item.id"
            >
            </el-option>
          </el-select>
        </p>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="setRoleVisible = false">取 消</el-button>
        <el-button type="primary" @click="setRole">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data() {
    //验证邮箱的规则
    let checkEmail = (rule, value, cb) => {
      const reg = /^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+(\.[a-zA-Z0-9_-])+/;
      if (reg.test(value)) {
        return cb();
      }
      cb(new Error("请输入合法的邮箱"));
    };
    //验证手机的规则
    let checkMobile = (rule, value, cb) => {
      let reg =
        /^(0|86|17951)?(13[0-9]|15[012356789]|17[678]|18[0-9]|14[57])[0-9]{8}$/;
      if (reg.test(value)) {
        return cb();
      }
      cb(new Error("请输入合法的手机号"));
    };

    return {
      userList: [],
      total: 0,
      //获取用户列表的参数对象
      queryInfo: {
        query: "",
        pagenum: 1, //当前页数
        pagesize: 2, //当前内每页显示的条数
      },
      dialogFormVisible: false, //控制弹窗的显示隐藏
      formLabelWidth: "80px", //控制弹窗的宽度
      //添加用户的表单数据
      addForm: {
        username: "",
        password: "",
        email: "",
        mobile: "",
      },
      editDialogVisible: false, //控制修改对话框显示与隐藏
      //修改用户的表单数据
      editForm: {},
      setRoleVisible: false, //控制分配角色对话框的显示隐藏
      usersInfo: {}, //用户对应的所有信息
      roleList: [], //所有的角色列表
      selectedRole: "", //选中的角色名称
      //添加表单的验证规则
      addRules: {
        username: [
          { required: true, message: "请输入用户名", trigger: "blur" },
          {
            min: 3,
            max: 10,
            message: "长度在 3 到 10 个字符",
            trigger: "blur",
          },
        ],
        password: [
          { required: true, message: "请输入密码", trigger: "blur" },
          {
            min: 6,
            max: 15,
            message: "长度在 6 到 15 个字符",
            trigger: "blur",
          },
        ],
        email: [
          { required: true, message: "请输入邮箱", trigger: "blur" },
          { validator: checkEmail, trigger: "blur" },
        ],
        mobile: [
          { required: true, message: "请输入手机号", trigger: "blur" },
          { validator: checkMobile, trigger: "blur" },
        ],
      },
    };
  },
  mounted() {
    this.getUserList();
  },
  methods: {
    //获取所有用户信息
    getUserList() {
      this.axios
        .get("users", {
          params: this.queryInfo,
        })
        .then((res) => {
          if (res.data.meta.status !== 200) {
            return this.$message.error("获取用户列表失败");
          }
          this.userList = res.data.data.users;
          this.total = res.data.data.total;
        });
    },
    //监听pagesize 改变的事件
    handleSizeChange(newSize) {
      this.queryInfo.pagesize = newSize;
      this.getUserList();
    },
    //监听页码值改变的事件
    handleCurrentChange(newPage) {
      this.queryInfo.pagenum = newPage;
      this.getUserList();
    },
    //修改用户状态
    userStateChanged(id, state) {
      this.axios.put(`users/${id}/state/${state}`).then((res) => {
        // console.log(res.data);
        if (res.data.meta.status !== 200) {
          state = !state;
          return this.$message.error("更新用户状态失败");
        }
        this.$message.success("更新用户状态成功");
      });
    },
    //监听用户对话框的关闭事件
    addDialogClosed() {
      this.$refs.addFormRef.resetFields();
    },
    // 添加用户
    addUser() {
      this.$refs.addFormRef.validate((valid) => {
        if (!valid) return;
        this.axios.post("users", this.addForm).then((res) => {
          // console.log(res);
          if (res.data.meta.status !== 201) {
            this.$message.error("添加用户失败");
          }
          this.$message.success("添加用户成功");
          this.dialogFormVisible = false;
          this.getUserList();
        });
      });
    },
    //显示修改用户信息对话框
    showEditDialog(id) {
      this.editDialogVisible = true;
      this.axios.get(`users/${id}`).then((res) => {
        // console.log(res.data.data);
        if (res.data.meta.status !== 200) {
          this.$message.error("查询用户信息失败");
        }
        this.editForm = res.data.data;
      });
    },
    //监听修改用户对话框的关闭事件
    editDialogClosed() {
      this.$refs.editFormRef.resetFields();
    },
    //修改用户信息
    editUser(id) {
      this.$refs.editFormRef.validate((valid) => {
        if (!valid) return;
        this.editDialogVisible = false;
        this.axios
          .put(`users/${id}`, {
            email: this.editForm.email,
            mobile: this.editForm.mobile,
          })
          .then((res) => {
            // console.log(res.data);
            if (res.data.meta.status !== 200) {
              this.$message.error("修改用户信息失败");
            }
            this.$message.success("修改用户信息成功");
            this.editDialogVisible = false;
            this.getUserList();
          });
      });
    },
    //删除用户
    delUser(id) {
      //询问用户是否删除
      this.$confirm("此操作将永久删除该用户, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then((res) => {
          if (res === "confirm") {
            this.axios.delete(`users/${id}`).then((res) => {
              if (res.data.meta.status !== 200) {
                this.$message.error("删除失败");
                return;
              }
              this.getUserList();
              this.$message({
                type: "success",
                message: "删除成功!",
              });
            });
          }
        })
        .catch((err) => {
          if (err === "cancel") {
            this.$message({
              type: "info",
              message: "已取消删除",
            });
          }
        });
    },
    //显示分配角色对话框
    showSetRole(usersInfo) {
      this.usersInfo = usersInfo;
      this.axios.get("roles").then((res) => {
        let result = res.data;
        if (result.meta.status !== 200) {
          return this.$message.error("获取角色失败");
        }
        this.roleList = result.data;
        console.log(result.data);
      });
      this.setRoleVisible = true;
    },
    //设置分配角色
    setRole() {
      if (!this.selectedRole) {
        return this.$message.error("请选择要分配的角色");
      }
      this.axios
        .put(`users/${this.usersInfo.id}/role`, { rid: this.selectedRole })
        .then((res) => {
          let result = res.data;
          if (result.meta.status !== 200) {
            return this.$message.error("更新角色失败");
          }
          this.$message.success("更新角色成功");
          this.getUserList();
          this.setRoleVisible = false;
        });
    },
    //重置分配角色对话框的选中项
    resetSelectRole() {
      this.selectedRole = "";
      this.usersInfo = {};
    },
  },
};
</script>

<style lang="scss" scoped>
.categories {
  .el-table {
    margin-top: 15px;
    font-size: 12px;
  }
  .el-pagination {
    margin-top: 15px;
    text-align: left;
  }
  .userInfo {
    text-align: left;
  }
  .el-select{
    width: 100%;
  }
}
</style>